import { Http } from "./http";

class Paging {
  offset;
  limit;
  req;
  url;
  locker = false;
  moreData = true;
  accumulator = [];
  constructor(req, limit = 10, offset = 1) {
    this.offset = offset;
    this.limit = limit;
    this.req = req;
    this.url = req.url;
  }
  async getMoreData() {
    if (!this.moreData) {
      return;
    }
    // console.log("this._getLocker()");
    // console.log(this._getLocker());
    // console.log(!this._getLocker());
    if (!this._getLocker()) {
      return;
    }

    const data = await this._actualGetData();
    // console.log("_actualGetData");
    // console.log(data);

    this._releaseLocker();
    return data;
  }
  async _actualGetData() {
    const req = this._getCurrentReq();

    let paging = await Http.request(req);

    if (!paging) {
      return null;
    }
    if (paging.total === 0) {
      return {
        empty: true,
        items: [],
        moreData: false,
        accumulator: []
      };
    }
    this.moreData = this._moreData(paging.total, this.offset);
    if (this.moreData) {
      this.offset += 1;
    }
    this._accumulator(paging.rows);
    return {
      empty: false,
      items: paging.rows,
      moreData: this.moreData,
      accumulator: this.accumulator
    };
  }
  _accumulator(items) {
    this.accumulator = this.accumulator.concat(items);
  }
  _moreData(totalPage, pageNum) {
    // return pageNum * this.limit < totalPage - 1;
    // return true;
    return (pageNum - 1) * this.limit < totalPage;
  }
  _getCurrentReq() {
    if (this.req.method === "post") {
      let data = {
        pageNum: this.offset,
        pageSize: this.limit
      };
      this.req.data = Object.assign({}, this.req.data, data);

      return this.req;
    } else {
      let url = this.url;
      const params = `pageNum=${this.offset}&pageSize=${this.limit}`;
      if (url.includes("?")) {
        url += "&" + params;
      } else {
        url += "?" + params;
      }
      this.req.url = url;
      return this.req;
    }
  }
  _getLocker() {
    if (this.locker) {
      return false;
    }
    this.locker = true;
    return true;
  }
  _releaseLocker() {
    this.locker = false;
  }
}
export { Paging };
